package controllers;

import play.*;
import play.mvc.*;
import vo.TwoWayTreeNode;

import java.util.*;

import org.joda.time.DateTime;
import org.joda.time.JodaTimePermission;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

import models.*;

public class Application extends Controller {

	public static void index() {
		render("/Application/index.html");
	}

	public static void ajaxData(String pageCode, String dateTime) {
		DateTimeFormatter formater = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
		Date startTime = DateTime.parse(dateTime + " 00:00:00", formater).toDate();
		Date endTime = DateTime.parse(dateTime + " 23:59:59", formater).toDate();
		List<RelationShip> rss = RelationShip.find("curPage=? and createTime>? and createTime<?", pageCode, startTime, endTime).fetch();
		RelationShip rs = rss.get(0);
		// 父节点
		List<TwoWayTreeNode> supPageNodes = new ArrayList<TwoWayTreeNode>();
		String supPages = rs.supPage.replaceAll("\\{", "").replaceAll("\\}", "");
		String[] supPagesArr = supPages.split(",");
		for (String supPage : supPagesArr) {
			TwoWayTreeNode node = new TwoWayTreeNode();
			String[] supPageCount = supPage.split(":");
			node.name = supPageCount[0].replaceAll("\"", "") + "(" + supPageCount[1] + ")";
			node.isparent = true;
			supPageNodes.add(node);
		}
		// 子节点
		List<TwoWayTreeNode> subPageNodes = new ArrayList<TwoWayTreeNode>();
		String subPages = rs.subPage.replaceAll("\\{", "").replaceAll("\\}", "");
		String[] subPagesArr = subPages.split(",");
		for (String subPage : subPagesArr) {
			TwoWayTreeNode node = new TwoWayTreeNode();
			String[] supPageCount = subPage.split(":");
			node.name = supPageCount[0].replaceAll("\"", "") + "(" + supPageCount[1] + ")";
			subPageNodes.add(node);
		}

		TwoWayTreeNode rootNode = new TwoWayTreeNode();
		rootNode.name = rs.curPage;
		rootNode.isparent = true;
		rootNode.parents = supPageNodes;
		rootNode.children = subPageNodes;

		renderJSON(rootNode);
	}
}